package com.java.rabbitmq.worker;

import com.java.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @author Woo_home
 * @create 2020/5/26 13:12
 */

public class ConsumerDemo {

    // 队列名称
    private static final String QUEUE_NAME = "test_worker_queue";

    public static void main(String[] args) throws Exception {
        // 获取连接
        Connection connection = ConnectionUtils.getConnection();

        // 获取 channel
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 定义一个消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 消息到达触发这个方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String s = new String(body, "utf-8");
                System.out.println("msg : " + s);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("done");
                }
            }
        };

        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
